package com.ruitu.mall_98_2.mine;

import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.beanu.arad.Arad;
import com.beanu.arad.base.my_base.MyBaseActivity;
import com.beanu.arad.utils.ToastUtils;
import com.beanu.arad.utils.UIUtils;
import com.beanu.arad.view.IdentifyingCode;
import com.beanu.arad.widget.EditTextCleanView;
import com.beanu.arad.widget.progressactivity.ProgressLayout;
import com.ruitu.mall_98_2.R;
import com.ruitu.mall_98_2.dao.APIRetrofit;
import com.ruitu.router_module.AppHolder;
import com.ruitu.router_module.bean.EventModel;
import com.ruitu.router_module.bean.api.BaseResult;
import com.ruitu.router_module.bean.api.SubscriberImpl;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class WithdrawDepositActivity extends MyBaseActivity {

    private LinearLayout ll_get_code;
    private LinearLayout ll_alipay_account;

    private TextView tv_tel;//手机号
    private TextView tv_next;
    private TextView tv_get_code;

    private TextView tv_alipay_account;//支付宝账号
    private EditText et_money;//提现金额
    private TextView tv_withdraw_deposit;//提现

    private int time = 60;
    private boolean isGeting = false;
    private AlertDialog alertDialog;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (!Arad.bus.isRegistered(this)) {
            Arad.bus.register(this);
        }
    }

    @Override
    protected int getLayoutRes() {
        return R.layout.activity_withdraw_deposit;
    }

    @Override
    protected ProgressLayout findProgressLayout() {
        return null;
    }

    @Override
    protected void initViews() {
        super.initViews();
        setHeadTitle("提现");
        ll_get_code = findViewById(R.id.ll_get_code);
        ll_alipay_account = findViewById(R.id.ll_alipay_account);

        tv_tel = findViewById(R.id.tv_tel);
        tv_next = findViewById(R.id.tv_next);
        tv_alipay_account = findViewById(R.id.tv_alipay_account);
        et_money = findViewById(R.id.et_money);
        tv_next.setOnClickListener(this);
        ll_alipay_account.setOnClickListener(this);
        tv_tel.setText(AppHolder.instance().getUser().getPhone().substring(0, 3) + "****" + AppHolder.instance().getUser().getPhone().substring(7, 11));

    }

    @Override
    protected void onResume() {
        super.onResume();
        if (AppHolder.instance().getUser().getAlipayUserInfo() != null) {
            tv_alipay_account.setText(AppHolder.instance().getUser().getAlipayUserInfo().getAlipayAccount());
        }
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        if (ll_alipay_account == v) {
            if (AppHolder.instance().getUser().getAlipayUserInfo() == null) {
                startActivity(BandingAlipayActivity.class);
            }
        }

        if (tv_next == v) {
            if (AppHolder.instance().getUser().getAlipayUserInfo() == null) {
                ToastUtils.showShort("请绑定支付宝账号");
                return;
            }
            if (!TextUtils.isEmpty(et_money.getText().toString())) {
                showGetCodeDialog();
            } else {
                ToastUtils.showShort("输入提现金额不能为空");
            }
        }

    }

    private EditTextCleanView et_code;
    private ImageView iv_verifactiion_code;

    private void showGetCodeDialog() {
        alertDialog = new AlertDialog.Builder(this).create();
        View view = View.inflate(this, R.layout.dialog_withdraw_deposit, null);
        et_code = view.findViewById(R.id.et_code);
        tv_get_code = view.findViewById(R.id.tv_get_code);
        TextView tv_cancle = view.findViewById(R.id.tv_cancle);
        tv_withdraw_deposit = view.findViewById(R.id.tv_withdraw_deposit);
        final EditText et_iv_verifactiion_code = view.findViewById(R.id.et_iv_verifactiion_code);
        iv_verifactiion_code = view.findViewById(R.id.iv_verifactiion_code);
        getVerifactionCode();
        tv_get_code.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.equals(et_iv_verifactiion_code.getText().toString().toLowerCase(), resultCode)) {
                    tv_get_code.setEnabled(false);
                    setGetCodeTime(60);
                    isGeting = true;
//                            et_code.setText(baseResult.getData().toString());
                    handler.sendEmptyMessageDelayed(979, 1000);
                    getVersionCode();
                } else {
                    ToastUtils.showShort("图片验证不正确");
                }
                getVerifactionCode();
            }

        });

        tv_cancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertDialog.dismiss();
                handler.removeMessages(979);
            }
        });

        tv_withdraw_deposit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String code = et_code.getText().toString();
                if (TextUtils.isEmpty(et_code.getText())) {
                    ToastUtils.showShort("验证码不能为空");
                    return;
                }
                showProgress();
                setWithdrawDeposit(code);
            }
        });
        iv_verifactiion_code.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getVerifactionCode();
            }
        });
        alertDialog.setCanceledOnTouchOutside(false);
        alertDialog.setView(view);
        alertDialog.show();
    }

    private String resultCode;

    private void getVerifactionCode() {
        iv_verifactiion_code.setImageBitmap(IdentifyingCode.getInstance().createBitmap());
        resultCode = IdentifyingCode.getInstance().getCode().toLowerCase();
    }

    //获取验证码
    public void getVersionCode() {
        APIRetrofit.getDefault().smsSend(AppHolder.instance().getUser().getPhone(), "7").subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new SubscriberImpl<BaseResult>() {
                    @Override
                    public void onError(Throwable e) {
                        ToastUtils.showShort("获取验证码失败");
                    }

                    @Override
                    public void onNext(BaseResult baseResult) {
                        if (baseResult.isSuccess()) {
                            ToastUtils.showShort(baseResult.getMsg());
                        } else {
                            ToastUtils.showShort(baseResult.getMsg());
                        }
                    }
                });
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 979) {
                if (isGeting) {
                    setGetCodeTime(--time);
                    handler.sendEmptyMessageDelayed(979, 1000);
                }
            }
        }
    };

    private void setGetCodeTime(int time) {
        if (time == 0) {
            isGeting = false;
            tv_get_code.setEnabled(true);
            tv_get_code.setText("获取验证码");
            this.time = 60;
        } else {
            tv_get_code.setText(time + "s后重新获取");
        }
    }

    private void setWithdrawDeposit(String code) {
        APIRetrofit.getDefault().putForward(AppHolder.instance().getUser().getAccountId(), et_money.getText().toString(), code)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())
                .subscribe(new SubscriberImpl<BaseResult<String>>() {
                    @Override
                    public void onError(Throwable e) {
                        hideProgress();
                        ToastUtils.showShort("提现失败");
                    }

                    @Override
                    public void onNext(BaseResult<String> stringBaseResult) {
                        hideProgress();
                        if (stringBaseResult.isSuccess()) {
                            alertDialog.dismiss();
                            UIUtils.showAlertDialog(getSupportFragmentManager(), "等待管理人员审核", "",
                                    "确定", "", new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            finish();
                                        }
                                    }, null);
                            ToastUtils.showShort(stringBaseResult.getMsg());
                        } else {
                            ToastUtils.showShort(stringBaseResult.getMsg());
                        }
                    }
                });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void setAliAccount(EventModel<String> eventModel) {
        if (eventModel.getEventCode() == 18121400) {
            tv_alipay_account.setText((String) eventModel.getEventObj());
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (Arad.bus.isRegistered(this)) {
            Arad.bus.unregister(this);
        }
    }
}
